package dbtools;

import java.sql.SQLException;

import dbtools.innertables.DBCounters;
import dbtools.structures.DBField;

public abstract class DBDatabase {
	public abstract DBTransaction createTransaction() throws SQLException;

	public String getSqlType(DBField fld) {
		return fld.getSqlType();
	}
	
	public long getCounterLong(String counterName, long initialValue) throws SQLException{
		DBTransaction transaction = null;
		try{
			transaction = createTransaction();
			DBCounters counterEnt = transaction.getByMainKey(DBCounters.class, DBCounters.buildKey(counterName));
			long retVal = 0;
			if (counterEnt == null){
				counterEnt = DBFactory.createInstance(DBCounters.class);
				counterEnt.counterName.setValue(counterName);
				counterEnt.longValue.setValue(initialValue);
				counterEnt.intValue.setValue(0);
				transaction.insert(counterEnt);
				retVal = initialValue;
			}else{
				retVal = counterEnt.longValue.getValue()+1;
				counterEnt.longValue.setValue(retVal);
				transaction.update(counterEnt);
			}
			transaction.commit();
			return retVal;
		}finally{
			doFinally(transaction);
		}
	}
	

	public int getCounterInt(String counterName, int initialValue) throws SQLException{
		DBTransaction transaction = null;
		try{
			transaction = createTransaction();
			DBCounters counterEnt = transaction.getByMainKey(DBCounters.class, DBCounters.buildKey(counterName));
			int retVal = 0;
			if (counterEnt == null){
				counterEnt = DBFactory.createInstance(DBCounters.class);
				counterEnt.counterName.setValue(counterName);
				counterEnt.longValue.setValue(new Long(0));
				counterEnt.intValue.setValue(initialValue);
				transaction.insert(counterEnt);
				retVal = initialValue;
			}else{
				retVal = counterEnt.intValue.getValue()+1;
				counterEnt.intValue.setValue(retVal);
				transaction.update(counterEnt);
			}
			transaction.commit();
			return retVal;
		}finally{
			doFinally(transaction);
		}
	}
	
	public static void doFinally(DBTransaction transaction) {
		if (transaction != null){
			try {
				transaction.rollback();
			} catch (SQLException e) {
			}
		}
	}
}
